package yxy.game.pm2.bean.module.rank.openserviceactive.herorushrank;

import org.redisson.api.RSet;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.module.BaseGameRedisBean;

/**
 * 开服冲榜-武将比拼
 * 查询和记录玩家获取的武将种类
 *
 *
 * @ClassName OpenServicePlayerHeroBean
 * @Author jingtao-zheng
 * @Date 2022/7/7 11:09
 * @Version 1.0
 **/
public class OpenServicePlayerHeroBean  extends BaseGameRedisBean {
    private String playerCode;
    private int heroId;

    public OpenServicePlayerHeroBean(String playerCode,int heroId) {
        this.playerCode = playerCode;
        this.heroId = heroId;
    }

    /**
     * 玩家是否拥有该武将
     * 没有就添加,并返回false
     */
    public boolean isHaveHero(){
        boolean contains = false;
        try {
            if (tryLock()) {
                RSet<String> playerHeroSet = getPlayerHeroSet();
                contains = playerHeroSet==null?false:playerHeroSet.contains(heroId);
                if (!contains){
                    setPlayerHeroSet();
                }
                return contains;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            unlock();
        }
        return contains;
    }

    /**
     * 获取玩家的武将set
     */
    private RSet<String> getPlayerHeroSet()  {
        try {
            return RedisManager.client(redis()).getSet(key());
        } catch (RedisException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 添加玩家新获得的武将
     */
    private void setPlayerHeroSet(){
        try {
            RSet<Object> set = RedisManager.client(redis()).getSet(key());
            set.add(heroId);
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    private String key(){
        return String.format("PLAYER:%s:HAVEHERO",playerCode);
    }

    @Override
    public String lockKey() {
        return String.format("lock:%s", key());
    }
}
